package com.xianxing.wxPay.controller;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.xianxing.common.util.ConvertToStringUtil;
import com.xianxing.common.util.MessageConstant;
import com.xianxing.common.util.Response;
import com.xianxing.wxPay.config.RabbitConfig;
import com.xianxing.wxPay.service.WxPayService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付接口
 * date: 2020/3/4
 * auth: 李金全
 */
@RestController
@RequestMapping("/wxpay")
public class WxPayController {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WxPayService wxPayService;
    /**
     * 本地扫码支付
     * @param orderId  订单id
     * @param money  订单金额
     * @return
     */
    @GetMapping("/nativePay/{orderId}/{money}")
    public Response nativePay(@PathVariable String orderId,@PathVariable Integer money){
        Map result = wxPayService.nativePay(orderId, money);
        result.put("payMoney","0.01");
        return Response.OK(MessageConstant.WXPAY_SUCCESS,result);
    }

    @RequestMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response)throws Exception{

        String xml = ConvertToStringUtil.convertToString(request.getInputStream());
        Map<String, String> map = WXPayUtil.xmlToMap(xml);
        //判断支付结果
        if(map.get("return_code").equals("SUCCESS")&&"SUCCESS".equals(map.get("result_code"))) {
            //返回结果是成功的
            //修改数据库订单信息为已支付并保存微信订单号
            HashMap<String, String> result = new HashMap<>();
            result.put("orderId",map.get("out_trade_no"));
            result.put("transaction_id",map.get("transaction_id"));

            rabbitTemplate.convertAndSend("", RabbitConfig.ORDER_PAY, JSON.toJSONString(result));
            //返回成功结果
            response.setContentType("text/html");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        }
    }
}
